package com.taiyuan.ty.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author : 周桓宇
 * @description : 文件上传工具
 * @createDate : 2025/3/26 下午1:21
 */
public class FileUtil {
    public static String upload(MultipartFile file, String uploadPath) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        String fileExtension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        // 确保有扩展名
        if (lastDotIndex > 0) {
            fileExtension = originalFilename.substring(lastDotIndex);
        } else {
            throw new IllegalArgumentException("无效的文件名，没有扩展名");
        }

        String newFileName = UUID.randomUUID().toString() + fileExtension;

        try {
            // 确保路径以文件分隔符结尾
            if (!uploadPath.endsWith(File.separator)) {
                uploadPath += File.separator;
            }
            // 将文件存储到指定路径
            File destFile = new File(Paths.get(uploadPath, newFileName).toString());
            file.transferTo(destFile);
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败", e);
        }
    }
}